package cn.dataservice.executor.jobs;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RuntimeUtil;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;

@JobHandler(value = "Fy4aTBBJob")
@Component
public class Fy4aTBBJob extends IJobHandler {
	
	@Value("${python_TBB}")
	private String tbbCMD;
	
	@Override
	public ReturnT<String> execute(String param) throws Exception {
		Date now = DateUtil.offsetHour(new Date(), -10);
		String ymdh = DateUtil.format(now, "yyyyMMddHHmm");
		ymdh = ymdh.substring(0, 11) + "0";
		String cmd = String.format(tbbCMD, ymdh);
		XxlJobLogger.log("TBB PYTHON JOB INVOKED!CMD={}", cmd);
		
		int exitValue = -1;
        BufferedReader bufferedReader = null;
        try {
            // command process
            Process process = RuntimeUtil.exec(cmd);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));

            // command log
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                XxlJobLogger.log(line);
            }

            // command exit
            process.waitFor();
            exitValue = process.exitValue();
        } catch (Exception e) {
            XxlJobLogger.log(e);
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        }

        if (exitValue == 0) {
            return IJobHandler.SUCCESS;
        } else {
            return new ReturnT<String>(IJobHandler.FAIL.getCode(), "command exit value("+exitValue+") is failed");
        }
	}

}
